
package com.hery.core;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class NettyHandler extends SimpleChannelInboundHandler {
    private final Map<String, NettyChannel> channels = new ConcurrentHashMap<String, NettyChannel>(); 
    public NettyHandler(){

    }

    public Map<String, NettyChannel> getChannels() {
        return channels;
    }


    @Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	 NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel());
         try {
             if (channel != null) {
                 channels.put(toAddressString((InetSocketAddress)ctx.channel().remoteAddress()), channel);
             }
         } finally {
             NettyChannel.removeChannelIfDisconnected(ctx.channel());
         }
	}

    private  String toAddressString(InetSocketAddress address) {
        return address.getAddress().getHostAddress() + ":" + address.getPort();
    }

    @Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    	NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel());
        try {
            channels.remove(toAddressString((InetSocketAddress)ctx.channel().remoteAddress()));
        } finally {
            NettyChannel.removeChannelIfDisconnected(ctx.channel());
        }
	}


	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object message)
			throws Exception {
		   NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel());
	        try {
	            //TODO:接收并处理
	        } finally {
	            NettyChannel.removeChannelIfDisconnected(ctx.channel());
	        }
		
	}



    @Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
    	NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel());
        try {
            //TODO:异常处理
        } finally {
            NettyChannel.removeChannelIfDisconnected(ctx.channel());
        }
	}




}